package pl.arekczogala.plati;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

public class ConnectionTCP {

	
	Integer port;

	public String err_msg = "";
	
	private InetAddress remoteIP;
	
	private Socket socket_tcp;	
	private PrintWriter output;
	OutputStream out;	
	BufferedReader input;
	
	public ConnectionTCP(InetAddress remoteIP, Integer port){
		
		this.remoteIP = remoteIP; 
		this.port = port;
		
		//causing problems -> 
		Log.v(LOG_TAG, "new instance with IP = "+this.remoteIP.toString()+" and port= "+this.port.toString() );
		
	}
	/*
	 * Connect to remote host
	 */
	public boolean connect(){
		
		try{
			
			socket_tcp = new Socket(this.remoteIP.toString(),this.port); 
	            	            
		 } catch (UnknownHostException e) {
	            // TODO Auto-generated catch block
	            this.err_msg = e.getMessage().toString();
	            return false;
		   } catch (IOException e) {
	            // TODO Auto-generated catch block
	            this.err_msg = e.getMessage().toString();
			    return false;
	
		   }
	return true;
	}
	
	
	
	/*
	 * Disconnect from host
	 */
	public boolean disconnect(){
		try{
			
			socket_tcp.close();
		 } catch (UnknownHostException e) {
	            
	            this.err_msg = e.getMessage().toString();
	            return false;
		   } catch (IOException e) {
	            // TODO Auto-generated catch block
			  
	            this.err_msg =  e.getMessage().toString();
	            return false;
	}
		return true;
	}
	public void send(String data){

        try{
	 	out = socket_tcp.getOutputStream();
	 	input = new BufferedReader(new InputStreamReader(socket_tcp.getInputStream()));
	 	output = new PrintWriter(socket_tcp.getOutputStream(),true); //Autoflush
        //output = new PrintWriter(out);
       // str = input.readLine();
        output.println();
		output.println(data);
	            
        }catch (UnknownHostException e) {
            
            this.err_msg = e.getMessage().toString();
            Log.d(LOG_TAG,e.getMessage().toString());
	   } catch (IOException e) {
            // TODO Auto-generated catch block		  
            this.err_msg =  e.getMessage().toString();
            Log.d(LOG_TAG,e.getMessage().toString());
}       

	}
	
	
	private static final String LOG_TAG = "ConnectionTCP";
}
